package deng.hibernate.examples;

import java.util.List;
import java.util.Properties;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;

public class HibernateSessionMain {
	
	private Session session;
	
	private boolean runInsertData = true;
	
	public static void main(String[] args) {
		new HibernateSessionMain().run();
	}
	
	public void run() {
		AnnotationConfiguration cfg = new AnnotationConfiguration();
		
		// Extra config per this package only.
		Properties extraProperties = new Properties();
		if (runInsertData) {
			extraProperties.setProperty("hibernate.hbm2ddl.auto", "create");
		}
		cfg.addProperties(extraProperties);
		cfg.addAnnotatedClass(Simple.class);
		
		SessionFactory sessionFactory = cfg.configure().buildSessionFactory();
		session = sessionFactory.getCurrentSession();
		Transaction tx = null;
		try {
			tx = session.beginTransaction();
			runExample();
			tx.commit();
		} catch (Throwable e) {
			if (tx.isActive()) {
				tx.rollback();
			}
			throw new RuntimeException(e);
		} finally {
			sessionFactory.close();
		}
	}

	private void runExample() {
		if (runInsertData) {
			runCreateData();
			session.flush();
			session.clear();
		}
		runQuery();
	}
	
	private void runCreateData() {
		for (int i = 0; i < 10; i++) {
			Simple m = new Simple();
			m.setName("Hello" + i + " World");
			session.persist(m);
		}
	}

	private void runQuery() {
		printQueryResult("from Simple");
	}

	public void printQueryResult(String queryString) {
		List<?> list = session.createQuery(queryString).list();
		for (Object object : list) {
			System.out.println(object);
		}
		System.out.println("Size= " + list.size());
	}
	
}
